package token

import (
	"crypto/rsa"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type JWTTokenGen struct {
	privateKey *rsa.PrivateKey
	issue      string
	NwFunc     func() time.Time
}

func NewJWTTokenGen(issue string, privateKey *rsa.PrivateKey) *JWTTokenGen {
	return &JWTTokenGen{
		issue:      issue,
		NwFunc:     time.Now,
		privateKey: privateKey,
	}
}

func (j *JWTTokenGen) GenerateToken(accountID string, expire time.Duration) (string, error) {
	now := j.NwFunc().Unix()
	claims := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.StandardClaims{
		Issuer:    j.issue,
		IssuedAt:  now,
		ExpiresAt: now + int64(expire.Seconds()),
		Subject:   string(accountID),
	})
	return claims.SignedString(j.privateKey)
}
